﻿using System;
using System.Diagnostics;

namespace BinarySearch
{
    class Program
    {

        static void Main(string[] args)
        {
            int[] buffer = new int[100000000];
            for (int i = 0; i < buffer.Length; i++)
             {
                buffer[i] = i;
            }

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            int index = BinarySearchFun(buffer, 99999999);
            Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds.ToString("F5"));

            stopwatch.Restart();

            int index2 = Fun(buffer, 99999999);
            Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds.ToString("F5"));
            Console.WriteLine($"Hello World! {index} {index2}");
        }

        /// <summary>
        /// 二分查找
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static int BinarySearchFun(int[] buffer, int value)
        {
            int low = 0;
            int high = buffer.Length - 1;
            while (low < high)
            {
                int mid = (low + high) / 2;
                if (buffer[mid] < value)
                {
                    low = mid;
                    if (low == high - 1)
                        break;
                }
                else
                {
                    high = mid;
                }
            }
            return high;
        }

        /// <summary>
        /// 普通遍历
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static int Fun(int[] buffer, int value)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == value)
                {
                    return i;
                }
            }
            return -1;
        }
    }
}
